package com.agp.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String bucketName;
    private String region;

    /**
     * 多文件上传
     *
     * @param
     * @param
     * @return
     */
    public List<String> uploadFile(MultipartFile[] images, Integer treeId, String role) throws Exception {
        if (images == null) {
            return null;
        }

        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        OSS ossClient = getOssClient();


        // 生成一个新的不重复的文件名
        List<String> urls = new ArrayList<>();
        try {
            for (MultipartFile image : images) {
                String originalFilename = image.getOriginalFilename();

                String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                String objectName = role + "/" + treeId + "/" + newFileName;
                byte[] fileBytes = image.getBytes();
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(fileBytes));

                // 上传文件。
                // ossClient.putObject(putObjectRequest);

                // 获取图片的访问路径
                String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
                log.info("图片上传成功，访问路径为：{}", url);
                urls.add(url);
            }
        } finally {
            ossClient.shutdown();
        }
        return urls;
    }

    //  用户上传头像图片
    public List<String> uploadFile(MultipartFile[] images, Long userId) throws Exception {
        if (images == null) {
            return null;
        }
        OSS ossClient = getOssClient();

        // 生成一个新的不重复的文件名
        List<String> urls = new ArrayList<>();
        try {
            for (MultipartFile image : images) {
                String originalFilename = image.getOriginalFilename();

                String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                String objectName = "userImage" + "/" + userId + newFileName;
                byte[] fileBytes = image.getBytes();
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(fileBytes));

                // 上传文件。
                // ossClient.putObject(putObjectRequest);

                // 获取图片的访问路径
                String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
                log.info("图片上传成功，访问路径为：{}", url);
                urls.add(url);
            }
        } finally {
            ossClient.shutdown();
        }
        return urls;
    }

    /**
     * Excel上传图片
     * @param fileBytes
     * @param userName
     * @return
     * @throws Exception
     */

    public String uploadFile(byte[] fileBytes, String userName ) throws Exception {
        if (fileBytes == null) {
            return null;
        }
        OSS ossClient = getOssClient();


        try {
                //获取当前年月日
            LocalDate currentDate = LocalDate.now();
            String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 自定义格式

                String newFileName = UUID.randomUUID() + ".jpg";
                String objectName = userName + "/" + formattedDate+"/" + newFileName;

                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(fileBytes));

                // 上传文件。
                // ossClient.putObject(putObjectRequest);

                // 获取图片的访问路径
                String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
                log.info("图片上传成功，访问路径为：{}", url);
              return url;
        } finally {
            ossClient.shutdown();
        }

    }


    // 上传不健康古树图片
    public List<String> uploadUnhealthyTreeImage(MultipartFile[] images) throws Exception {
        if (images == null) {
            return null;
        }
        OSS ossClient = getOssClient();
        List<String> urls = new ArrayList<>();
        try {
            for (MultipartFile image : images) {
                String originalFilename = image.getOriginalFilename();

                String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                LocalDate currentDate = LocalDate.now();
                String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 自定义格式

                String objectName = "unhealthyTreeImage" + "/" +formattedDate+"/"+ newFileName;
                byte[] fileBytes = image.getBytes();
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(fileBytes));
                // 上传文件。
                 ossClient.putObject(putObjectRequest);

                // 获取图片的访问路径
                String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
                log.info("图片上传成功，访问路径为：{}", url);
                urls.add(url);
            }
        }finally {
            ossClient.shutdown();
        }
        return urls;
    }

    private OSS getOssClient() throws ClientException {
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
        return ossClient;
    }


}
